﻿using System;
using System.Collections.Generic;
using System.Linq;
using DoNet.Utils;

namespace DoNet.TenPay
{
    /// <summary>
    /// 平台证书 接口
    /// </summary>
    public class CertApi
    {
        /// <summary>
        /// 获取平台证书列表
        /// </summary>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="apiKeyV3">商户号API密钥V3</param>
        /// <returns></returns>
        public static List<CertsModel> GetCertificates(string merchantId, string apiKeyV3)
        {
            List<CertsModel> result = null;
            try
            {
                string url = DomainUtil.GetDomainName(Config.GetWechatPayUrl(), "/v3/certificates");
                ResponseHandlerV3 responseHandler = new ResponseHandlerV3(url, merchantId);
                var resData = responseHandler.ResponseBody;
                if (!string.IsNullOrEmpty(resData))
                {
                    var certs = JsonUtil.JsonToT<CertificatesResult>(resData);

                    #region 解密证书
                    result = new List<CertsModel>();
                    foreach (var item in certs.data)
                    {
                        var serial_no = item.serial_no;
                        var effective_time = Convert.ToDateTime(item.effective_time);
                        var expire_time = Convert.ToDateTime(item.expire_time);
                        var encrypt_certificate = item.encrypt_certificate;

                        CertsModel model = new CertsModel()
                        {
                            SerialNo = serial_no,
                            EffectiveTime = effective_time,
                            ExpireTime = expire_time,
                            PlainCertificate = AesGcmUtil.Decrypt(apiKeyV3, encrypt_certificate.ciphertext,  encrypt_certificate.associated_data)
                        };
                        result.Add(model);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Log.Error("Wechat-V3—CertApi—GetCertificates", ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 根据平台证书序列号 获取对应平台证书解密后内容 
        /// </summary>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="apiKeyV3">商户号API密钥V3</param>
        /// <param name="serialNo">接口返回的证书序列号</param>
        /// <returns></returns>
        public static string GetCertsResult(string merchantId, string apiKeyV3, string serialNo)
        {
            string result = "";
            var certs = GetCertificate(merchantId, apiKeyV3, serialNo);
            if (certs != null)
            {
                result = certs.PlainCertificate;
            }
            return result;
        }

        /// <summary>
        /// 获取平台证书
        /// </summary>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="apiKeyV3">商户号API密钥V3</param>
        /// <returns></returns>
        public static CertsModel GetCertsResult(string merchantId, string apiKeyV3)
        {
            CertsModel certs = new CertsModel();
            string cacheKey = "Certificates_" + merchantId;
            var obj = CacheUtil.GetCache(cacheKey);
            if (obj != null)
            {
                certs = (CertsModel)obj;

                var dateNow = DateTime.Now;
                if (certs.ExpireTime < dateNow)
                {
                    //已过期，重新获取
                    certs = GetCertificate(merchantId, apiKeyV3);
                    if (certs != null)
                    {
                        //先删除缓存
                        CacheUtil.RemoveCache(cacheKey);
                        //加入缓存
                        CacheUtil.SetCache(cacheKey, certs, 0);
                    }
                }
            }
            else
            {
                certs = GetCertificate(merchantId, apiKeyV3);
                if (certs != null)
                {
                    //加入缓存
                    CacheUtil.SetCache(cacheKey, certs, 0);
                }
            }
            return certs;
        }

        /// <summary>
        /// 获取最新的平台证书（即：证书启用时间较晚的证书）
        /// </summary>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="apiKeyV3">商户号API密钥V3</param>
        /// <returns></returns>
        public static CertsModel GetCertificate(string merchantId, string apiKeyV3)
        {
            var certsModel = GetCertificates(merchantId, apiKeyV3).OrderByDescending(x => x.EffectiveTime).FirstOrDefault();
            return certsModel;
        }

        /// <summary>
        /// 获取平台证书 根据平台证书序列号
        /// </summary>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="apiKeyV3">商户号API密钥V3</param>
        /// <param name="serialNo">接口返回的证书序列号</param>
        /// <returns></returns>
        public static CertsModel GetCertificate(string merchantId, string apiKeyV3, string serialNo)
        {
            var certsModel = GetCertificates(merchantId, apiKeyV3).Select(x => { x.SerialNo = serialNo; return x; }).FirstOrDefault();
            return certsModel;
        }
    }
}
